<script setup lang="ts">
import { User, Lock, Warning, Male } from '@element-plus/icons-vue'
import { Ref, computed, reactive, ref } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import useUserStore from '@/store/modules/user'
import { ElNotification } from 'element-plus'
import { getTime } from '@/utils/time'
import Identify from '@/components/VerifyCode/index.vue'
import Title from '@/layout/title/index.vue'
import setting from '@/setting'

// VerifyCode import
// 获取路由器
let $router = useRouter()
let $route = useRoute()
let loading = ref(false)
const isRegister = ref(true)
let LoginFormData = reactive({ jobNumber: '123456', password: '000000' })
let RegisterFormData = reactive({
  jobNumber: '111111',
  userName: 'admin',
  password: '000000',
  repassword: '000000',
})
let userStore = useUserStore()

// 登录方法
// async 函数返回一个 Promise 对象，可以使用 then 方法添加回调函数。
const login = async () => {
  loading.value = true
  try {
    console.log('开始登录，参数：', LoginFormData)
    // 登录成功
    const loginResult = await userStore.userLogin(LoginFormData)
    console.log('登录结果：', loginResult)

    // 获取用户信息
    console.log('开始获取用户信息')
    const userInfoResult = await userStore.userInfo()
    console.log('获取用户信息结果：', userInfoResult)

    //判断登录路由路径当中是否有query 参数，如果有就前往query参数跳转 没有就跳转至首页
    let redirect: any = $route.query.redirect
    console.log('准备跳转到：', redirect || '/home')
    await $router.push(redirect || '/home')

    ElNotification({
      type: 'success',
      message: '欢迎回来',
      title: `Hi, ${getTime()}-好`,
    })
  } catch (error: any) {
    console.error('登录失败：', error)
    loading.value = false
    ElNotification({
      type: 'error',
      message: error.message || '登录失败',
    })
  } finally {
    loading.value = false
  }
}

// 注册
const register = async () => {
  loading.value = true
  try {
    await userStore.userRegister(RegisterFormData)
    $router.push({ path: '/login' })
    ElNotification({
      type: 'success',
      message: '注册成功',
    })
    loading.value = false
  } catch (error) {
    loading.value = false
    ElNotification({
      type: 'error',
      message: '注册失败',
    })
  }
}

// 自定义校验规则函数
const validatorUserName = (rules: any, value: any, callback: any) => {
  //  rules 为校验规则对象，value 表单元素内容 callback 符合条件 callback放行通过，不符合条件注入错误信息
  if (value && value.length >= 5) {
    callback()
  } else {
    callback(new Error('账号长度至少5位'))
  }
}
const validatorPassWord = (rule: any, value: any, callback: any) => {
  if (value && value.length >= 6 && value.length <= 10) {
    callback()
  } else {
    callback(new Error('密码长度至少6位'))
  }
}

const checkRePassWord = (rule: any, value: any, callback: any) => {
  if (value === '') {
    callback(new Error('请再次确定密码'))
  } else if (value == RegisterFormData.password) {
    callback(new Error('请确保两次输入的密码一样'))
  }
}

// 定义表单校验需要的配置对象
const rules = {
  jobNumber: [
    {
      trigger: 'change',
      validator: validatorUserName,
    },
  ],
  password: [
    {
      trigger: 'change',
      validator: validatorPassWord,
    },
  ],
  repassword: [
    {
      trigger: 'change',
      validator: checkRePassWord,
    },
  ],
}
</script>
<template>
  <div class="login_container">
    <el-row>
      <el-col :span="12" :xs="0"></el-col>
      <el-col :span="12" :xs="24">
        <el-card class="login_form">
          <div style="width: 100%; height: 100%">
            <img :src="setting.logo" alt="" />
            <h1>{{ setting.title }}</h1>
          </div>
          <el-form
            ref="loginForms"
            autocomplete="off"
            v-if="isRegister"
            :rules="rules"
            :model="LoginFormData"
          >
            <el-form-item prop="jobNumber">
              <el-input
                :prefix-icon="User"
                v-model="LoginFormData.jobNumber"
                clearable
                placeholder="用户名"
                size="large"
              ></el-input>
            </el-form-item>
            <el-form-item prop="password">
              <el-input
                type="password"
                :prefix-icon="Lock"
                v-model="LoginFormData.password"
                show-password
                size="large"
                placeholder="请输入密码"
                clearable
              ></el-input>
            </el-form-item>
            <!-- <el-form-item prop="verifyCode">
              <el-input :prefix-icon="Warning" show-password placeholder="验证码" size="large" maxlength="4">
                <template #append></template>
              </el-input>
            </el-form-item> -->
            <el-form-item class="login">
              <el-button
                :loading="loading"
                class="login_btn"
                type="primary"
                size="default"
                @click="login"
                plain
              >
                登录
              </el-button>
              <el-button
                :loading="loading"
                class="is_register_btn"
                type="primary"
                size="default"
                @click="isRegister = !isRegister"
                plain
              >
                未注册
              </el-button>
            </el-form-item>
          </el-form>
          <el-form
            ref="loginForms"
            autocomplete="off"
            :rules="rules"
            :model="RegisterFormData"
            v-else
          >
            <el-form-item prop="jobNumber">
              <el-input
                :prefix-icon="User"
                v-model="RegisterFormData.jobNumber"
                clearable
                placeholder="请输入工号"
                size="large"
              ></el-input>
            </el-form-item>
            <el-form-item prop="userName">
              <el-input
                name="userName"
                :prefix-icon="Lock"
                v-model="RegisterFormData.userName"
                clearable
                type="userName"
                placeholder="请输入用户名"
                size="large"
              ></el-input>
            </el-form-item>
            <el-form-item prop="password">
              <el-input
                name="password"
                :prefix-icon="Lock"
                v-model="RegisterFormData.password"
                show-password
                clearable
                type="password"
                placeholder="请输入密码"
                size="large"
              ></el-input>
            </el-form-item>
            <el-form-item prop="repassword">
              <el-input
                :prefix-icon="Lock"
                type="password"
                v-model="RegisterFormData.repassword"
                show-password
                clearable
                placeholder="请输入再次密码"
                size="large"
              ></el-input>
            </el-form-item>
            <el-form-item class="register">
              <el-button
                :loading="loading"
                class="register_btn"
                type="primary"
                size="default"
                plain
                @click="register"
              >
                注册
              </el-button>
              <el-button
                class="reback"
                type="info"
                :underline="false"
                @click="isRegister = !isRegister"
              >
                <el-icon>
                  <back />
                </el-icon>
                返回
              </el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>
<style lang="scss" scoped>
.login_container {
  width: 100%;
  height: 100vh;
  background: url('@/assets/images/background.jpg') no-repeat;
  background-size: cover;
  position: fixed;

  .login_form {
    border-radius: 25px;
    position: relative;
    width: 55%;
    top: 25vh;
    left: 10vw;
    padding: 10px;
    background: white;

    img {
      width: auto;
      height: 40px;
      float: left;
      margin-left: 20px;
      position: relative;
    }

    h1 {
      background: linear-gradient(
        to right,
        rgb(96, 192, 240),
        rgb(122, 121, 121)
      );
      -webkit-background-clip: text;
      -webkit-text-fill-color: transparent;
      font-size: calc(100vw * 42 / 1920);
      text-align: center;
      font-weight: 700;
      margin-bottom: 40px;
      margin-top: -10px;
    }

    .login {
      display: center;
    }

    .register {
      display: center;
    }

    .login_btn {
      width: 45%;
    }

    .is_register_btn {
      margin-left: auto;

      width: 50%;
    }

    .register_btn {
      width: 45%;
    }

    .reback {
      margin-left: auto;
      width: 50%;
    }

    .logo {
      position: absolute;
    }
  }
}

.el-card {
  box-shadow: rgba(0, 0, 0, 0.24) 0px 3px 8px;
}

:deep(.el-input-group__append, .el-input-group__prepend) {
  padding: 0;
}
</style>
